import { Order, Cargo, DashboardStats } from '../types';

// API 基础配置
const API_BASE_URL = '/api'; // 使用/api前缀，通过Vite代理到后端

// 通用请求函数
const request = async <T>(
  endpoint: string,
  options: RequestInit = {}
): Promise<T> => {
  const url = `${API_BASE_URL}${endpoint}`;
  
  const config: RequestInit = {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
    ...options,
  };

  // 如果有token，添加到请求头
  const token = localStorage.getItem('token');
  if (token) {
    config.headers = {
      ...config.headers,
      'Authorization': token, // 直接发送token，不加Bearer前缀
    };
  }

  try {
    const response = await fetch(url, config);
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const result = await response.json();
    
    // 检查后端返回的Result结构
    if (result.code !== undefined) {
      if (result.code === 200) {
        return result.data;
      } else {
        throw new Error(result.message || '请求失败');
      }
    }
    
    return result;
  } catch (error) {
    console.error('API请求错误:', error);
    throw error;
  }
};

// 登录接口
export const loginApi = {
  // 用户名密码登录
  async loginByUsername(username: string, password: string) {
    return request<{
      token: string;
      userInfo: {
        username: string;
        realName: string;
        email: string;
        phone: string;
        createTime: string;
      };
    }>('/user/loginByUserName', {
      method: 'POST',
      body: JSON.stringify({
        userName: username, // 字段映射：前端username -> 后端userName
        pwd: password,      // 字段映射：前端password -> 后端pwd
      }),
    });
  },
};

// 货物管理接口（对接Product接口）
export const cargoApi = {
  // 查询货物列表
  async getCargos(params?: { 
    page?: number; 
    limit?: number; 
    productName?: string;
    specification?: string;
    skuCode?: string; // 添加SKU编码参数
  }): Promise<{ data: Cargo[]; total: number }> {
    const result = await request<{
      list: Array<{
        skuCode: number;
        productName: string;
        specification?: string;
        unit: string;
        createTime: string;
        updateTime: string;
      }>;
      totalCount: number;
    }>('/product/selectList', {
      method: 'POST',
      body: JSON.stringify({
        pageNum: params?.page || 1,
        pageSize: params?.limit || 10,
        productName: params?.productName,
        specification: params?.specification,
        skuCode: params?.skuCode ? parseInt(params.skuCode) : undefined, // 传递SKU编码参数，转换为数字类型
      }),
    });

    // 字段映射：后端Product -> 前端Cargo
    const data: Cargo[] = result.list.map(item => ({
      id: item.skuCode.toString(),
      name: item.productName,
      specification: item.specification,
      unit: item.unit,
      createdAt: item.createTime,
      updatedAt: item.updateTime,
    }));

    return {
      data,
      total: result.totalCount,
    };
  },

  // 新增货物
  async createCargo(cargo: Omit<Cargo, 'id' | 'createdAt' | 'updatedAt'>): Promise<Cargo> {
    await request<string>('/product/add', {
      method: 'POST',
      body: JSON.stringify({
        productName: cargo.name,
        specification: cargo.specification,
        // unit字段在后端ProductDTO中没有，使用默认值
      }),
    });

    // 由于后端只返回成功消息，我们需要构造返回对象
    return {
      id: Date.now().toString(), // 临时ID
      name: cargo.name,
      specification: cargo.specification,
      unit: cargo.unit,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
  },

  // 更新货物
  async updateCargo(id: string, updates: Partial<Cargo>): Promise<Cargo | null> {
    await request<string>('/product/update', {
      method: 'POST',
      body: JSON.stringify({
        skuCode: parseInt(id),
        productName: updates.name,
        specification: updates.specification,
        unit: updates.unit,
      }),
    });

    // 由于后端只返回成功消息，我们需要构造返回对象
    return {
      id,
      name: updates.name || '',
      specification: updates.specification,
      unit: updates.unit || '',
      createdAt: '', // 后端没有返回，使用空字符串
      updatedAt: new Date().toISOString(),
    };
  },

  // 删除货物
  async deleteCargo(id: string): Promise<boolean> {
    try {
      await request<string>(`/product/delete?skuCode=${id}`, {
        method: 'GET',
      });
      return true;
    } catch (error) {
      console.error('删除货物失败:', error);
      return false;
    }
  },

  // 获取单个货物详情
  async getCargo(id: string): Promise<Cargo | null> {
    // 后端没有提供单个货物查询接口，暂时返回null
    // 可以通过查询列表接口实现
    return null;
  },
};

// 订单管理接口
export const orderApi = {
  // 查询订单列表
  async getOrders(params?: { 
    status?: string; 
    orderType?: string; 
    page?: number; 
    limit?: number;
    userName?: string;
    phone?: string;
    orderId?: string; // 添加订单ID参数
  }): Promise<{ data: Order[]; total: number }> {
    const result = await request<{
      list: Array<{
        orderId: number;
        userName: string;
        phone: string;
        orderDate: string;
        orderTime: string;
        totalRolls: number;
        orderType: string;
        createTime: string;
      }>;
      totalCount: number;
    }>('/order/queryOrder', {
      method: 'POST',
      body: JSON.stringify({
        pageNum: params?.page || 1,
        pageSize: params?.limit || 10,
        userName: params?.userName,
        phone: params?.phone,
        orderType: params?.orderType, // 直接传递中文值
        orderId: params?.orderId ? parseInt(params.orderId) : undefined, // 传递订单ID参数，转换为数字类型
        // 注意：后端没有status字段，前端的status筛选暂时无法使用
      }),
    });

    // 字段映射：后端Order -> 前端Order
    const data: Order[] = result.list.map(item => ({
      id: item.orderId.toString(),
      orderNumber: item.orderId.toString(), // 直接使用后端返回的orderId作为订单编号
      userName: item.userName,
      phone: item.phone,
      totalRolls: item.totalRolls,
      orderType: item.orderType as '镇内订单' | '镇外订单', // 直接使用后端返回的中文值
      orderDate: item.orderDate,
      orderTime: item.orderTime,
      status: 'completed' as const, // 后端没有status字段，默认为completed
      createdAt: item.createTime,
      updatedAt: item.createTime, // 后端没有updateTime，使用createTime
      products: [], // 需要单独查询订单详情
      notes: '', // 后端没有notes字段
    }));

    return {
      data,
      total: result.totalCount,
    };
  },

  // 新增订单
  async createOrder(order: Omit<Order, 'id' | 'createdAt' | 'updatedAt' | 'orderNumber'>): Promise<Order> {
    await request<string>('/order/addOrder', {
      method: 'POST',
      body: JSON.stringify({
        userName: order.userName,
        phone: order.phone,
        orderDate: order.orderDate,
        orderTime: order.orderTime,
        orderType: order.orderType, // 直接传递中文值
        orderDetailList: order.products.map(p => ({
          productId: parseInt(p.productId),
          rolls: p.rolls,
        })),
      }),
    });

    // 由于后端只返回成功消息，我们需要构造返回对象
    return {
      id: Date.now().toString(),
      orderNumber: Date.now().toString(), // 使用时间戳作为订单编号，与后端格式保持一致
      userName: order.userName,
      phone: order.phone,
      totalRolls: order.totalRolls,
      orderType: order.orderType, // 直接使用中文值
      orderDate: order.orderDate,
      orderTime: order.orderTime,
      status: 'completed',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      products: order.products,
      notes: order.notes,
    };
  },

  // 更新订单
  async updateOrder(id: string, updates: Partial<Order>): Promise<Order | null> {
    await request<string>('/order/updateOrder', {
      method: 'POST',
      body: JSON.stringify({
        orderId: parseInt(id),
        userName: updates.userName,
        phone: updates.phone,
        orderDate: updates.orderDate,
        orderTime: updates.orderTime,
        orderType: updates.orderType, // 直接传递中文值
      }),
    });

    // 由于后端只返回成功消息，我们需要构造返回对象
    return {
      id,
      orderNumber: id, // 直接使用id作为订单编号
      userName: updates.userName || '',
      phone: updates.phone || '',
      totalRolls: updates.totalRolls || 0,
      orderType: updates.orderType || '镇内订单', // 默认值使用中文
      orderDate: updates.orderDate || '',
      orderTime: updates.orderTime || '',
      status: 'completed',
      createdAt: '',
      updatedAt: new Date().toISOString(),
      products: updates.products || [],
      notes: updates.notes,
    };
  },

  // 删除订单
  async deleteOrder(id: string): Promise<boolean> {
    try {
      await request<string>(`/order/deleteOrder/${id}`, {
        method: 'GET',
      });
      return true;
    } catch (error) {
      console.error('删除订单失败:', error);
      return false;
    }
  },

  // 获取订单详情
  async getOrderDetails(orderId: string) {
    return request<Array<{
      skuCode: number;
      rolls: number;
      productName: string;
      specification: string;
      unit: string;
    }>>(`/order/queryOrderDetail/${orderId}`, {
      method: 'POST',
    });
  },

  // 获取单个订单
  async getOrder(id: string): Promise<Order | null> {
    // 后端没有提供单个订单查询接口，暂时返回null
    return null;
  },
};

// 数据分析接口
export const analyticsApi = {
  // 获取大屏数据
  async getOrderData(yearMonth: string) {
    return request<{
      largeScreenVO: {
        month: string;
        orderCount: number;
        totalRolls: number;
        customerCount: number;
      };
      largeScreenPieVOs: Array<{
        month: string;
        orderType: string;
        orderCount: number;
      }>;
      largeScreenCargoVO: Array<{
        skuCode: string;
        productName: string;
        specification: string;
        unit: string;
        month: string;
        totalOutbound: number;
        orderCount: number;
      }>;
      largeScreenLineVOs: Array<{
        orderDay: string;
        totalOrders: number;
        totalOutbound: number;
      }>;
      cargoCount: number;
    }>(`/order/queryOrderData?yearMonth=${yearMonth}`, {
      method: 'POST',
    });
  },

  // 获取仪表盘统计数据（使用订单数据计算）
  async getDashboardStats(): Promise<DashboardStats> {
    try {
      const currentMonth = new Date().toISOString().slice(0, 7); // YYYY-MM格式
      const data = await this.getOrderData(currentMonth);
      
      return {
        totalOrders: data.largeScreenVO.orderCount,
        pendingOrders: 0, // 后端数据中所有订单都是完成状态
        completedOrders: data.largeScreenVO.orderCount,
        exceptionOrders: 0,
        totalRevenue: 0, // 后端没有财务数据，暂时设为0
        totalCost: 0,
        activeVehicles: 0, // 后端没有车辆数据，暂时设为0
        totalVehicles: 0,
        onTimeDeliveryRate: 0.95, // 固定值
        customerSatisfaction: 4.8, // 固定值
      };
    } catch (error) {
      console.error('获取仪表盘数据失败:', error);
      // 返回默认值
      return {
        totalOrders: 0,
        pendingOrders: 0,
        completedOrders: 0,
        exceptionOrders: 0,
        totalRevenue: 0,
        totalCost: 0,
        activeVehicles: 0,
        totalVehicles: 0,
        onTimeDeliveryRate: 0.95,
        customerSatisfaction: 4.8,
      };
    }
  },
};

// 导出所有API
export const api = {
  login: loginApi,
  cargo: cargoApi,
  order: orderApi,
  analytics: analyticsApi,
}; 